package useragent

import (
	"fmt"
	"math/rand"
	"strings"

	"gitee.com/liumou_site/GoUserAgent/devices"
)

// generateWithDeviceInfo 使用设备信息生成UserAgent
func (u *UserAgentGenerator) generateWithDeviceInfo(options *generateOptions) string {
	deviceInfo := options.deviceInfo

	// 根据品牌和型号生成合适的UserAgent
	var patterns []userAgentPattern

	// 根据设备类型选择对应的模式
	var deviceType DeviceType
	if deviceInfo.Type == "tablet" {
		deviceType = Tablet
	} else {
		deviceType = Mobile
	}

	// 根据品牌选择对应的操作系统
	var osType OS
	switch deviceInfo.Brand {
	case devices.Apple:
		osType = IOS
	case devices.Samsung, devices.Xiaomi, devices.Huawei, devices.Oppo:
		osType = Android
	default:
		osType = Android
	}

	// 筛选符合条件的模式
	for _, pattern := range userAgentPatterns {
		if pattern.device == deviceType && pattern.os == osType {
			patterns = append(patterns, pattern)
		}
	}

	if len(patterns) == 0 {
		return ""
	}

	selectedPattern := patterns[rand.Intn(len(patterns))]
	versions := browserVersions[selectedPattern.browser]
	if len(versions) == 0 {
		return ""
	}

	version := versions[rand.Intn(len(versions))]

	// 根据设备信息自定义UserAgent
	return u.buildCustomUserAgent(selectedPattern, deviceInfo, version)
}

// generateWithBrand 使用品牌信息生成UserAgent
func (u *UserAgentGenerator) generateWithBrand(options *generateOptions) string {
	// 获取有效的操作系统类型
	var targetOS string
	if len(options.osList) > 0 {
		for _, os := range options.osList {
			switch os {
			case IOS:
				targetOS = "ios"
			case Android:
				targetOS = "android"
			}
			if targetOS != "" {
				break
			}
		}
	}

	// 如果没有指定品牌，使用默认品牌列表
	brands := options.brands
	if len(brands) == 0 {
		brands = devices.GetAllBrands()
	}

	// 根据操作系统过滤品牌
	var validBrands []devices.DeviceBrand
	for _, brand := range brands {
		if targetOS == "" || devices.GetOSByBrand(brand) == targetOS {
			validBrands = append(validBrands, brand)
		}
	}

	if len(validBrands) == 0 {
		return u.Generate()
	}

	// 随机选择一个有效品牌
	brand := validBrands[rand.Intn(len(validBrands))]

	// 获取该品牌的随机型号
	model := devices.GetRandomModelByBrand(brand)

	// 创建设备信息
	deviceInfo := &DeviceInfo{
		Brand: brand,
		Model: model,
	}

	// 根据型号名称判断设备类型
	if strings.Contains(strings.ToLower(model), "ipad") ||
		strings.Contains(strings.ToLower(model), "tab") ||
		strings.Contains(strings.ToLower(model), "pad") {
		deviceInfo.Type = "tablet"
	} else {
		deviceInfo.Type = "phone"
	}

	// 使用设备信息生成
	options.deviceInfo = deviceInfo
	return u.generateWithDeviceInfo(options)
}

// generateWithModels 使用指定的型号生成UserAgent
func (u *UserAgentGenerator) generateWithModels(options *generateOptions) string {
	if len(options.models) == 0 {
		return u.generateWithBrand(options)
	}

	// 获取有效的操作系统类型
	var targetOS string
	if len(options.osList) > 0 {
		// 如果指定了操作系统，使用第一个
		for _, os := range options.osList {
			switch os {
			case IOS:
				targetOS = "ios"
				break
			case Android:
				targetOS = "android"
				break
			}
			if targetOS != "" {
				break
			}
		}
	}

	// 过滤符合操作系统要求的品牌
	var validBrands []devices.DeviceBrand
	
	// 如果指定了品牌，只考虑指定的品牌
	if len(options.brands) > 0 {
		for _, brand := range options.brands {
			if _, exists := options.models[brand]; exists {
				if targetOS == "" || devices.GetOSByBrand(brand) == targetOS {
					validBrands = append(validBrands, brand)
				}
			}
		}
	} else {
		// 如果没有指定品牌，考虑所有品牌
		for brand := range options.models {
			if targetOS == "" || devices.GetOSByBrand(brand) == targetOS {
				validBrands = append(validBrands, brand)
			}
		}
	}
	
	if len(validBrands) == 0 {
		return u.generateWithBrand(options)
	}
	
	// 随机选择一个有效品牌
	brand := validBrands[rand.Intn(len(validBrands))]
	models := options.models[brand]
	
	if len(models) == 0 {
		return u.generateWithBrand(options)
	}
	
	// 从指定的型号中随机选择一个
	model := models[rand.Intn(len(models))]
	
	// 创建设备信息
	deviceInfo := &DeviceInfo{
		Brand: brand,
		Model: model,
	}
	
	// 根据型号名称判断设备类型
	if strings.Contains(strings.ToLower(model), "ipad") ||
		strings.Contains(strings.ToLower(model), "tab") ||
		strings.Contains(strings.ToLower(model), "pad") {
		deviceInfo.Type = "tablet"
	} else {
		deviceInfo.Type = "phone"
	}
	
	// 使用设备信息生成
	return u.generateWithDeviceInfo(&generateOptions{
		deviceTypes:   options.deviceTypes,
		osList:        options.osList,
		browsers:      options.browsers,
		deviceInfo:    deviceInfo,
		useDeviceInfo: true,
	})
}

// buildCustomUserAgent 构建自定义UserAgent
func (u *UserAgentGenerator) buildCustomUserAgent(pattern userAgentPattern, deviceInfo *DeviceInfo, version string) string {
	// 根据设备信息构建真实的UserAgent
	
	brand := deviceInfo.Brand
	model := deviceInfo.Model
	
	switch pattern.browser {
	case Firefox:
		version2 := browserVersions[pattern.browser][rand.Intn(len(browserVersions[pattern.browser]))]
		
		// Firefox格式
		if brand == devices.Apple {
			// iOS Firefox
			return fmt.Sprintf("Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/%s Mobile/15E148 Safari/605.1.15", version)
		} else {
			// Android Firefox - 使用实际设备型号
			return fmt.Sprintf("Mozilla/5.0 (Android 11; Mobile; %s; rv:%s) Gecko/%s Firefox/%s", model, version, version2, version)
		}
		
	case Chrome:
		// Chrome格式
		if brand == devices.Apple {
			// iOS Chrome
			return fmt.Sprintf("Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/%s Mobile/15E148 Safari/604.1", version)
		} else {
			// Android Chrome
			return fmt.Sprintf("Mozilla/5.0 (Linux; Android 11; %s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36", model, version)
		}
		
	case Safari:
		// Safari格式
		if brand == devices.Apple {
			if deviceInfo.Type == "tablet" {
				return fmt.Sprintf("Mozilla/5.0 (iPad; CPU OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/%s Mobile/15E148 Safari/604.1", version)
			} else {
				return fmt.Sprintf("Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/%s Mobile/15E148 Safari/604.1", version)
			}
		} else {
			// 其他品牌使用Chrome格式
			return fmt.Sprintf("Mozilla/5.0 (Linux; Android 11; %s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36", model, version)
		}
		
	case Edge:
		version2 := browserVersions[pattern.browser][rand.Intn(len(browserVersions[pattern.browser]))]
		
		// Edge格式
		if brand == devices.Apple {
			// iOS Edge
			return fmt.Sprintf("Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) EdgiOS/%s Mobile/15E148 Safari/604.1", version)
		} else {
			// Android Edge
			return fmt.Sprintf("Mozilla/5.0 (Linux; Android 11; %s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36 Edg/%s", model, version, version2)
		}
		
	default:
		// 默认使用Android格式
		return fmt.Sprintf("Mozilla/5.0 (Linux; Android 11; %s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36", model, version)
	}
}

// GenerateMobile 生成移动设备UserAgent（快捷方法）
func (u *UserAgentGenerator) GenerateMobile() string {
	return u.WithDeviceTypes(Mobile).Generate()
}

// GenerateTablet 生成平板设备UserAgent（快捷方法）
func (u *UserAgentGenerator) GenerateTablet() string {
	return u.WithDeviceTypes(Tablet).Generate()
}

// GenerateiOS 生成iOS设备UserAgent（快捷方法）
func (u *UserAgentGenerator) GenerateiOS() string {
	return u.WithOS(IOS).Generate()
}

// GenerateAndroid 生成Android设备UserAgent（快捷方法）
func (u *UserAgentGenerator) GenerateAndroid() string {
	return u.WithOS(Android).Generate()
}

// GenerateByBrand 根据品牌生成UserAgent
func (u *UserAgentGenerator) GenerateByBrand(brand devices.DeviceBrand) string {
	return u.WithBrands(brand).Generate()
}

// GenerateByDevice 根据具体设备信息生成UserAgent
func (u *UserAgentGenerator) GenerateByDevice(deviceInfo *DeviceInfo) string {
	return u.GenerateWithOptions(WithDeviceInfo(deviceInfo))
}

// GenerateRandomMobile 生成随机移动设备UserAgent
func GenerateRandomMobile() string {
	gen := New()
	return gen.WithDeviceTypes(Mobile).Generate()
}

// GenerateRandomTablet 生成随机平板设备UserAgent
func GenerateRandomTablet() string {
	gen := New()
	return gen.WithDeviceTypes(Tablet).Generate()
}

// GenerateRandomByBrand 根据品牌生成随机UserAgent
func GenerateRandomByBrand(brand devices.DeviceBrand) string {
	gen := New()
	return gen.WithBrands(brand).Generate()
}